package com.todaynews.home;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.viewpager.widget.ViewPager;
import com.common.bean.InfoResult;
import com.common.cache.SpCache;
import com.common.ui.barlibrary.ImmersionBar;
import com.common.ui.fragment.BaseFragment;
import com.common.ui.views.colortrackview.ColorClipTabLayout;
import com.common.utils.GsonUtil;
import com.common.utils.screen.DensityUtil;
import com.todaynews.R;
import com.todaynews.utils.Constant;
import com.todaynews.home.adapter.ChannelPagerAdapter;
import com.todaynews.listener.OnChannelListener;
import com.todaynews.model.Channel;
import com.video.jzvd.Jzvd;
import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseFragment implements OnChannelListener {

    private TextView tv_search;
    private List<Channel> selectedChannels = new ArrayList<>();
    private List<Channel> unSelectedChannels = new ArrayList<>();
    private List<NewsListFragment> channelFragments = new ArrayList<>();
    private String[] channelCodes;
    private ColorClipTabLayout tab_channel;
    private ChannelPagerAdapter channelPagerAdapter;
    private ViewPager vp_content;
    private ImageView iv_operation;

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.color_D43D3D).init();
    }

    @Override
    public boolean isImmersionBarEnabled() {
        return true;
    }

    @Override
    public void init() {
        initChannelData();
        initChannelFragments();
        channelPagerAdapter = new ChannelPagerAdapter(channelFragments,selectedChannels,getChildFragmentManager());
        vp_content.setAdapter(channelPagerAdapter);
        vp_content.setOffscreenPageLimit(selectedChannels.size());
        tab_channel.setTabPaddingLeftAndRight(DensityUtil.getInstance().dpToPx(10), DensityUtil.getInstance().dpToPx(10));
        tab_channel.setupWithViewPager(vp_content);
        tab_channel.post(new Runnable() {
            @Override
            public void run() {
                //设置最小宽度，使其可以在滑动一部分距离
                ViewGroup slidingTabStrip = (ViewGroup) tab_channel.getChildAt(0);
                slidingTabStrip.setMinimumWidth(slidingTabStrip.getMeasuredWidth() + iv_operation.getMeasuredWidth());
            }
        });
        //隐藏指示器
        tab_channel.setSelectedTabIndicatorHeight(0);
        vp_content.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //当页签切换的时候，如果有播放视频，则释放资源
                Jzvd.releaseAllVideos();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void bind(View view) {
        super.bind(view);
        tv_search = view.findViewById(R.id.tv_search);
        tab_channel = view.findViewById(R.id.tab_channel);
        vp_content = view.findViewById(R.id.vp_content);
        iv_operation = view.findViewById(R.id.iv_operation);
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onItemMove(int starPos, int endPos) {

        listMove(selectedChannels, starPos, endPos);
        listMove(channelFragments, starPos, endPos);
    }

    @Override
    public void onMoveToMyChannel(int starPos, int endPos) {
        //移动到我的频道
        Channel channel = unSelectedChannels.remove(starPos);
        selectedChannels.add(endPos, channel);
        NewsListFragment newsFragment = new NewsListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constant.CHANNEL_CODE, channel.channelCode);
        bundle.putBoolean(Constant.IS_VIDEO_LIST, channel.channelCode.equals(channelCodes[1]));
        newsFragment.setArguments(bundle);
        channelFragments.add(newsFragment);
    }

    @Override
    public void onMoveToOtherChannel(int starPos, int endPos) {
       //移动到推荐频道
        unSelectedChannels.add(endPos, selectedChannels.remove(starPos));
        channelFragments.remove(starPos);
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {

    }

    @Override
    protected void onFail(int what, InfoResult t) {

    }

    /**
     * 初始化已选频道和未选频道的数据
     */
    private void initChannelData() {

        String selectedChannelJson = SpCache.getInstance().get(Constant.SELECTED_CHANNEL_JSON, "");
        String unselectChannel = SpCache.getInstance().get(Constant.UNSELECTED_CHANNEL_JSON, "");
        if (TextUtils.isEmpty(selectedChannelJson) || TextUtils.isEmpty(unselectChannel)) {
            //本地没有title
            String[] channels = getResources().getStringArray(R.array.channel);
            String[] channelCodes = getResources().getStringArray(R.array.channel_code);
            //默认添加了全部频道
            for (int i = 0; i < channelCodes.length; i++) {
                String title = channels[i];
                String code = channelCodes[i];
                selectedChannels.add(new Channel(title, code));
            }
            selectedChannelJson = GsonUtil.getInstance().toJson(selectedChannels);//将集合转换成json字符串
            SpCache.getInstance().put(Constant.SELECTED_CHANNEL_JSON, selectedChannelJson);//保存到sp
        } else {
            //之前添加过
            List<Channel> selectedChannel = GsonUtil.getInstance().jsonToList(selectedChannelJson, Channel.class);
            List<Channel> unselectedChannel = GsonUtil.getInstance().jsonToList(unselectChannel, Channel.class);
            selectedChannels.addAll(selectedChannel);
            unSelectedChannels.addAll(unselectedChannel);
        }
    }

    /**
     * 初始化已选频道的fragment的集合
     */
    private void initChannelFragments() {
        channelCodes = getResources().getStringArray(R.array.channel_code);
        for (Channel channel : selectedChannels) {
            NewsListFragment newsFragment = new NewsListFragment();
            Bundle bundle = new Bundle();
            bundle.putString(Constant.CHANNEL_CODE, channel.channelCode);
            bundle.putBoolean(Constant.IS_VIDEO_LIST, channel.channelCode.equals(channelCodes[1]));//是否是视频列表页面,根据判断频道号是否是视频
            newsFragment.setArguments(bundle);
            channelFragments.add(newsFragment);//添加到集合中
        }
    }

    private void listMove(List datas, int starPos, int endPos) {
        Object o = datas.get(starPos);
        //先删除之前的位置
        datas.remove(starPos);
        //添加到现在的位置
        datas.add(endPos, o);
    }

}
